package com.zzw.util;

import android.database.Cursor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ZZW on 2016/4/18.
 */
public class QuestionDao {

    // 插入数据
    public static void insertData(Map<String,Object> map){
        String sql = "insert into ques_ans(question,answer) values(?,?)";
        Globals.util.getWritableDatabase().execSQL(sql,new Object[]{map.get("question"),map.get("answer")});
    }

    // 读取全部数据
    public static List<Map<String,Object>> loadData(){
        List<Map<String,Object>> values = new ArrayList<>();
        String sql = "select id question answer from ques_ans";
        Cursor c = Globals.util.getReadableDatabase().rawQuery(sql,null);
        c.moveToFirst();
        while(!c.isAfterLast()){
            Map<String,Object> map = new HashMap<>();
            map.put("question",c.getString(1));
            map.put("answer", c.getString(2));
            values.add(map);
            c.moveToNext();
        }
        c.close();
        return values;
    }

    // 分页读取数据
    public static List<Map<String,Object>> loadDataPage(int pagenum,int pagesize,String keyword){
        List<Map<String,Object>> values = new ArrayList<>();
        String sql = "select id question answer from ques_ans where question like ? limit ?,?";
        Cursor c = Globals.util.getReadableDatabase().rawQuery(sql,new String[]{"%"+keyword+"&",pagenum * pagesize - pagesize +"",pagesize+""});
        c.moveToFirst();
        while(!c.isAfterLast()){
            Map<String,Object> map = new HashMap<>();
            map.put("question",c.getString(1));
            map.put("answer", c.getString(2));
            map.put("showFlag",false);
            values.add(map);
            c.moveToNext();
        }
        c.close();
        return values;
    }

    // 查询总记录数
    public static int getCount(String keyword){
        int recordCount = 0;
        String sql = "select count(*) from ques_ans where question like ?";
        Cursor c = Globals.util.getReadableDatabase().rawQuery(sql,new String[]{"%"+keyword+"%"});
        c.moveToFirst();
        recordCount = c.getInt(0);
        c.close();
        return recordCount;
    }

    // 删除数据
    public static void deleteAllData(){
        String sql = "delete from ques_ans";
        Globals.util.getWritableDatabase().execSQL(sql);
    }
}
